package com.shawn.admin.interceptor;

import com.shawn.commons.utils.JwtUtils;
import com.shawn.model.entity.Admin;
import io.jsonwebtoken.Claims;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1、获取头信息
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer ", "");
        //2、调用service根据token查询用户
        Claims claims = JwtUtils.getClaims(token);
        Admin admin = new Admin();
        admin.setId(claims.get("id",Long.class));
        admin.setUsername(claims.get("username",String.class));
        //4、将对象存入
        ThreadContext.setAdmin(admin);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadContext.clear();
    }
}
